package org.yzh.web.service;

import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.yzh.web.config.MinioConfig;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.FileInputStream;

@Service
@Slf4j
public class MinioFileService {
    @Getter
    private MinioClient minioClient;

    @Getter
    private final MinioConfig minioConfig;

    public MinioFileService(@Autowired(required = false) MinioConfig minioConfig) {
        if (minioConfig == null){
            minioConfig = new MinioConfig();
            minioConfig.setEnable(false);
        }
        this.minioConfig = minioConfig;
    }

    @PostConstruct
    public void init() {
        if (false == minioConfig.isEnable()){
            return;
        }
        minioClient = MinioClient.builder()
                .endpoint(minioConfig.getUrl())
                .credentials(minioConfig.getAccessKey(), minioConfig.getSecretKey())
                .build();
        try {
            String bucketName = minioConfig.getBucketName();
            boolean bucketExists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!bucketExists) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
                log.info("Bucket {} was not found in MinIO and has been created.", bucketName);
            }
            log.info("MinIO Initialization completed!");
        } catch (Exception e) {
            log.error("Failed to connect to MinIO!", e);
        }
    }

    public boolean uploadFile(File file) {
        try {
            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(minioConfig.getBucketName())
                            .object(file.getAbsolutePath())
                            .stream(new FileInputStream(file), file.length(), -1)
                            .build());
        } catch (Exception e) {
            log.error("文件上传失败,发生异常!",e);
            return false;
        }
        return true;
    }
}
